<!DOCTYPE html>
<html>
<head><meta name="generator" content="Hexo 3.8.0">
    

    
<!-- Tencent Speed -->
<script>var _speedMark = new Date()</script>
<!-- End Tencent Speed -->
<!-- Tencent Analysis -->
<script async src="//tajs.qq.com/stats?sId=false."></script>
<!-- End Tencent Analysis -->


    



    <meta charset="utf-8">
    
    
    <meta name="google-site-verification" content="CUm1VNyzpZuuHWWTWLOVfbkoMiz6Q9ccqUY5rMp9vcI">

    
    
    <title>【Effective java第二版整理】第二条： 遇到多个构造器参数时要考虑构造器 | Edward</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="Effective java,java书籍,学习">
    <meta name="description" content="静态工厂和构造器有个共同的局限性：它们都不能很好的扩展到大量的可选参数。   对于这样的类，应该是用哪种构造器或者静态方法来编写呢？ 重构构造器：   程序员一向习惯采用重叠构造器（telescoping constructor) 模式，在这种模式下，你提供第一个只有必要参数的构造器，第二个构造器有一个可选参数，第三个有两个可选参数，依次类推，最后一个构造器包含所有的可选参数。   12345">
<meta name="keywords" content="Effective java,java书籍,学习">
<meta property="og:type" content="article">
<meta property="og:title" content="【Effective java第二版整理】第二条： 遇到多个构造器参数时要考虑构造器">
<meta property="og:url" content="http://springcloud.xn--ses554g/2018/12/13/Effective_java_002/index.html">
<meta property="og:site_name" content="Edward">
<meta property="og:description" content="静态工厂和构造器有个共同的局限性：它们都不能很好的扩展到大量的可选参数。   对于这样的类，应该是用哪种构造器或者静态方法来编写呢？ 重构构造器：   程序员一向习惯采用重叠构造器（telescoping constructor) 模式，在这种模式下，你提供第一个只有必要参数的构造器，第二个构造器有一个可选参数，第三个有两个可选参数，依次类推，最后一个构造器包含所有的可选参数。   12345">
<meta property="og:locale" content="default">
<meta property="og:updated_time" content="2019-10-10T11:12:18.940Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【Effective java第二版整理】第二条： 遇到多个构造器参数时要考虑构造器">
<meta name="twitter:description" content="静态工厂和构造器有个共同的局限性：它们都不能很好的扩展到大量的可选参数。   对于这样的类，应该是用哪种构造器或者静态方法来编写呢？ 重构构造器：   程序员一向习惯采用重叠构造器（telescoping constructor) 模式，在这种模式下，你提供第一个只有必要参数的构造器，第二个构造器有一个可选参数，第三个有两个可选参数，依次类推，最后一个构造器包含所有的可选参数。   12345">
    
        <link rel="alternate" type="application/atom+xml" title="Edward" href="/atom.xml">
    
    <link rel="shortcut icon" href="/img/favicon.ico">
    <link rel="stylesheet" href="//unpkg.com/hexo-theme-material-indigo@latest/css/style.css">
    <script>window.lazyScripts=[]</script>

    <!-- custom head -->
    

    <script>
        (function(){
            var bp = document.createElement('script');
            var curProtocol = window.location.protocol.split(':')[0];
            if (curProtocol === 'https'){
                bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
            }
            else{
                bp.src = 'http://push.zhanzhang.baidu.com/push.js';
            }
            var s = document.getElementsByTagName("script")[0];
            s.parentNode.insertBefore(bp, s);
        })();
    </script>

</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu">
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap" style="background-image:url(/img/brand.jpg)">
      <div class="brand" style="padding-top: 30%;">
        <a href="/" class="avatar waves-effect waves-circle waves-light">
          <img src="/img/123.png">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">Edward</h5>
          <a href="mailto:zqmssbd@qq.com" title="zqmssbd@qq.com" class="mail">zqmssbd@qq.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/">
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
          
            <li class="waves-block waves-effect">
              <a href="/archives">
                <i class="icon icon-lg icon-archives"></i>
                Archives
              </a>
            </li>
          
            <li class="waves-block waves-effect">
              <a href="/tags">
                <i class="icon icon-lg icon-tags"></i>
                Tags
              </a>
            </li>
          
            <li class="waves-block waves-effect">
              <a href="/categories">
                <i class="icon icon-lg icon-th-list"></i>
                Categories
              </a>
            </li>
          
            <li class="waves-block waves-effect">
              <a href="https://github.com/zqmssbd" target="_blank">
                <i class="icon icon-lg icon-github"></i>
                Github
              </a>
            </li>
          
            <li class="waves-block waves-effect">
              <a href="https://weibo.com/5333276247" target="_blank">
                <i class="icon icon-lg icon-weibo"></i>
                Weibo
              </a>
            </li>
          
            <li class="waves-block waves-effect">
              <a href="https://gitee.com/Edward-Z" target="_blank">
                <i class="icon icon-lg icon-link"></i>
                码云
              </a>
            </li>
          
      </ul>
        <div id="tp-weather-widget"></div>
        <script>
            (function(a,h,g,f,e,d,c,b){b=function(){d=h.createElement(g);c=h.getElementsByTagName(g)[0];d.src=e;d.charset="utf-8";d.async=1;c.parentNode.insertBefore(d,c)};a["SeniverseWeatherWidgetObject"]=f;a[f]||(a[f]=function(){(a[f].q=a[f].q||[]).push(arguments)});a[f].l=+new Date();if(a.attachEvent){a.attachEvent("onload",b)}else{a.addEventListener("load",b,false)}}(window,document,"script","SeniverseWeatherWidget","//cdn.sencdn.com/widget2/static/js/bundle.js?t="+parseInt((new Date().getTime() / 100000000).toString(),10)));
            window.SeniverseWeatherWidget('show', {
                flavor: "bubble",
                location: "WT3Q0FW9ZJ3Q",
                geolocation: true,
                language: "zh-Hans",
                unit: "c",
                theme: "auto",
                token: "74eabe8a-0b6b-4a56-86ac-c773a4d98218",
                hover: "enabled",
                container: "tp-weather-widget"
            })
        </script>

        <link rel="stylesheet" href="/css/APlayer.css">
        <div id="player" class="aplayer aplayer-withlist aplayer-fixed" data-id="3895885" data-server="netease" data-type="playlist" data-order="random" data-fixed="true" data-listfolded="false" data-theme="#2D8CF0"></div>
        <script src="/js/APlayer.min.js"></script>
        <script src="/js/Meting.min.js"></script>

        


        

    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">【Effective java第二版整理】第二条： 遇到多个构造器参数时要考虑构造器</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">【Effective java第二版整理】第二条： 遇到多个构造器参数时要考虑构造器</h1>
        <h5 class="title">你真的还不够，不够勤奋和努力。</h5>
        <h5 class="subtitle">
            
                <time datetime="2018-12-13T08:33:49.000Z" itemprop="datePublished" class="page-time">
  2018-12-13
</time>


	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/Effective-java/">Effective java</a></li></ul>

            
        </h5>
    </div>

    

    <script>
        (function(){
            var bp = document.createElement('script');
            var curProtocol = window.location.protocol.split(':')[0];
            if (curProtocol === 'https'){
                bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
            }
            else{
                bp.src = 'http://push.zhanzhang.baidu.com/push.js';
            }
            var s = document.getElementsByTagName("script")[0];
            s.parentNode.insertBefore(bp, s);
        })();
    </script>
</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap post-toc-shrink" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#重构构造器："><span class="post-toc-number">1.</span> <span class="post-toc-text">重构构造器：</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#JavaBeans模式"><span class="post-toc-number">2.</span> <span class="post-toc-text">JavaBeans模式</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#采用Builder模式"><span class="post-toc-number">3.</span> <span class="post-toc-text">采用Builder模式</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#总结"><span class="post-toc-number">4.</span> <span class="post-toc-text">总结</span></a></li></ol>
            <!--<div id="toc" class="toc-article">-->
                <!--<strong class="toc-title">文章目录</strong>-->
                <!--<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#重构构造器："><span class="toc-number">1.</span> <span class="toc-text">重构构造器：</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#JavaBeans模式"><span class="toc-number">2.</span> <span class="toc-text">JavaBeans模式</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#采用Builder模式"><span class="toc-number">3.</span> <span class="toc-text">采用Builder模式</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#总结"><span class="toc-number">4.</span> <span class="toc-text">总结</span></a></li></ol>-->
            <!--</div>-->
        </nav>
    </aside>




<article id="post-Effective_java_002" class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">【Effective java第二版整理】第二条： 遇到多个构造器参数时要考虑构造器</h1>
        <div class="post-meta">
            <time class="post-time" title="2018-12-13 16:33:49" datetime="2018-12-13T08:33:49.000Z" itemprop="datePublished">2018-12-13</time>

            
	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/Effective-java/">Effective java</a></li></ul>



            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style="display:none">
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <p>  静态工厂和构造器有个共同的局限性：它们都不能很好的扩展到大量的可选参数。</p>
<p>  对于这样的类，应该是用哪种构造器或者静态方法来编写呢？</p>
<h2 id="重构构造器："><a href="#重构构造器：" class="headerlink" title="重构构造器："></a>重构构造器：</h2><p>   程序员一向习惯采用重叠构造器（telescoping constructor) 模式，在这种模式下，你提供第一个只有必要参数的构造器，第二个构造器有一个可选参数，第三个有两个可选参数，依次类推，最后一个构造器包含所有的可选参数。</p>
  <figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line">package 重叠构造器;</span><br><span class="line">    </span><br><span class="line">    public class NutritionFacts &#123;</span><br><span class="line">        private final int servingSize; // (mL) required</span><br><span class="line">        private final int servings; // (per container) required</span><br><span class="line">        private final int calories; // optional</span><br><span class="line">        private final int fat; // (g) optional</span><br><span class="line">        private final int sodium; // (mg) optional</span><br><span class="line">        private final int carbohydrate; // (g) optional</span><br><span class="line">    </span><br><span class="line">        public NutritionFacts(int servingSize, int servings) &#123;</span><br><span class="line">            this(servingSize, servings, 0);</span><br><span class="line">        &#125;</span><br><span class="line">    </span><br><span class="line">        public NutritionFacts(int servingSize, int servings, int calories) &#123;</span><br><span class="line">            this(servingSize, servings, calories, 0);</span><br><span class="line">        &#125;</span><br><span class="line">    </span><br><span class="line">        public NutritionFacts(int servingSize, int servings, int calories, int fat) &#123;</span><br><span class="line">            this(servingSize, servings, calories, fat, 0);</span><br><span class="line">        &#125;</span><br><span class="line">    </span><br><span class="line">        public NutritionFacts(int servingSize, int servings, int calories, int fat,</span><br><span class="line">                              int sodium) &#123;</span><br><span class="line">            this(servingSize, servings, calories, fat, sodium, 0);</span><br><span class="line">        &#125;</span><br><span class="line">    </span><br><span class="line">        public NutritionFacts(int servingSize, int servings, int calories, int fat,</span><br><span class="line">                              int sodium, int carbohydrate) &#123;</span><br><span class="line">            this.servingSize = servingSize;</span><br><span class="line">            this.servings = servings;</span><br><span class="line">            this.calories = calories;</span><br><span class="line">            this.fat = fat;</span><br><span class="line">            this.sodium = sodium;</span><br><span class="line">            this.carbohydrate = carbohydrate;</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p> 缺点：重构构造器模式可行，但是当有许多参数的时候，客户端代码会很难编写，并且会很难阅读，如果客户端不小心颠倒了其中两个的顺序，编译器也不会出错，但是程序运行时会出现错误的行为。</p>
<h2 id="JavaBeans模式"><a href="#JavaBeans模式" class="headerlink" title="JavaBeans模式"></a>JavaBeans模式</h2><p>在这种模式下，调用一个无参构造器来创建对象，然后调用setter方法来设置每个必要的参数，以及每个相关的可选参数。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">package 重叠构造器;</span><br><span class="line"></span><br><span class="line">public class NutritionFacts1 &#123;</span><br><span class="line">    private int servingSize = -1;</span><br><span class="line">    private int servings = -1;</span><br><span class="line">    private int calories = 0;</span><br><span class="line">    private int fat = 0;</span><br><span class="line">    private int sodium = 0;</span><br><span class="line">    private int carbohydrate = 0;</span><br><span class="line"></span><br><span class="line">    public void setServingSize(int servingSize) &#123;</span><br><span class="line">        this.servingSize = servingSize;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setServings(int servings) &#123;</span><br><span class="line">        this.servings = servings;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setCalories(int calories) &#123;</span><br><span class="line">        this.calories = calories;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setFat(int fat) &#123;</span><br><span class="line">        this.fat = fat;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setSodium(int sodium) &#123;</span><br><span class="line">        this.sodium = sodium;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void setCarbohydrate(int carbohydrate) &#123;</span><br><span class="line">        this.carbohydrate = carbohydrate;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public <span class="function"><span class="title">NutritionFacts1</span></span>() &#123;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>缺点：在构造过程中javabean可能处于不一致的状态<br>javabean模式阻止了把类做成不可变的可能（需要额外的努力来保证线程安全）</p>
<h2 id="采用Builder模式"><a href="#采用Builder模式" class="headerlink" title="采用Builder模式"></a>采用Builder模式</h2><p>不直接生成对象，而是让客户端利用所有必要的参数调用构造器（或者静态工厂），得到一个builder对象。额庵后客户端在builder对象上调用类似于setter的方法，来设置每个相关的可选参数。最后，客户端调用无参的build方法来生成不可改变的对象。这个builder是它构建的类的静态成员类。下面就是它的实例：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br></pre></td><td class="code"><pre><span class="line">package 重叠构造器;</span><br><span class="line"></span><br><span class="line">public class NutritionFacts3 &#123;</span><br><span class="line">    private final int servingSize;</span><br><span class="line">    private final int servings;</span><br><span class="line">    private final int calories;</span><br><span class="line">    private final int fat;</span><br><span class="line">    private final int sodium;</span><br><span class="line">    private final int carbohydrate;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    //一个内部类</span><br><span class="line">    //以后维护的时候，添加新参数的时候也很方便</span><br><span class="line">    public static class Builder &#123;</span><br><span class="line">        // Required parameters</span><br><span class="line">        private final int servingSize;</span><br><span class="line">        private final int servings;</span><br><span class="line">        private int calories = 0;</span><br><span class="line">        private int fat = 0;</span><br><span class="line">        private int carbohydrate = 0;</span><br><span class="line">        private int sodium = 0;</span><br><span class="line"></span><br><span class="line">        public Builder(int servingSize, int servings) &#123;</span><br><span class="line">            this.servingSize = servingSize;</span><br><span class="line">            this.servings = servings;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        public Builder calories(int val) &#123;</span><br><span class="line">            calories = val;</span><br><span class="line">            <span class="built_in">return</span> this;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        public Builder fat(int val) &#123;</span><br><span class="line">            fat = val;</span><br><span class="line">            <span class="built_in">return</span> this;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        public Builder carbohydrate(int val) &#123;</span><br><span class="line">            carbohydrate = val;</span><br><span class="line">            <span class="built_in">return</span> this;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        public Builder sodium(int val) &#123;</span><br><span class="line">            sodium = val;</span><br><span class="line">            <span class="built_in">return</span> this;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        public NutritionFacts3 <span class="function"><span class="title">build</span></span>() &#123;</span><br><span class="line">            <span class="built_in">return</span> new NutritionFacts3(this);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    //构造函数需要传builder</span><br><span class="line">    //可以使用单个builder构建多个对象</span><br><span class="line">    private NutritionFacts3(Builder builder) &#123;</span><br><span class="line">        servingSize = builder.servingSize;</span><br><span class="line">        servings = builder.servings;</span><br><span class="line">        calories = builder.calories;</span><br><span class="line">        fat = builder.fat;</span><br><span class="line">        sodium = builder.sodium;</span><br><span class="line">        carbohydrate = builder.carbohydrate;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        //具有安全性和可读性</span><br><span class="line">        //build的时候才会验证参数是否正确</span><br><span class="line">        NutritionFacts3 cocaCola = new NutritionFacts3.Builder(240, 8)</span><br><span class="line">                .calories(100).sodium(35).carbohydrate(27).build();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>builder模式的不足：Builder模式比重叠构造器模式还要冗长，因此很多参数的时候才用它。</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>简而言之，如果一个类的构造器或者静态工厂中具有多个参数，设计这种类的时候，Builder模式就是种不错的选择，特别是当大多数参数都是可选的时候。与使用传统的重叠构造器模式相比，使用Builder模式的客户端代码将更易于阅读和编写，构建器也比JavaBeans更加安全。</p>

        </div>

        <blockquote class="post-copyright">
    
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2019-10-10T11:12:18.940Z" itemprop="dateUpdated">2019-10-10 19:12:18</time>
</span><br>


        
    </div>
    
    <footer>
        <a href="http://springcloud.xn--ses554g">
            <img src="/img/123.png" alt="Edward">
            Edward
        </a>
    </footer>
</blockquote>

        


        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Effective-java/">Effective java</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/java书籍/">java书籍</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/学习/">学习</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://springcloud.xn--ses554g/2018/12/13/Effective_java_002/&title=《【Effective java第二版整理】第二条： 遇到多个构造器参数时要考虑构造器》 — Edward&pic=http://springcloud.xn--ses554g/img/123.png" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://springcloud.xn--ses554g/2018/12/13/Effective_java_002/&title=《【Effective java第二版整理】第二条： 遇到多个构造器参数时要考虑构造器》 — Edward&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://springcloud.xn--ses554g/2018/12/13/Effective_java_002/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《【Effective java第二版整理】第二条： 遇到多个构造器参数时要考虑构造器》 — Edward&url=http://springcloud.xn--ses554g/2018/12/13/Effective_java_002/&via=http://springcloud.xn--ses554g" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://springcloud.xn--ses554g/2018/12/13/Effective_java_002/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/2018/12/14/hello-world/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">Hello World</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/2018/12/13/Effective_java_001/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">【Effective java第二版整理】第一条： 静态工厂代替构造器</h4>
      </a>
    </div>
  
</nav>



    











    <!-- Valine Comments -->
    <div class="comments vcomment" id="comments"></div>
    <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
    <script src="//unpkg.com/valine@latest/dist/Valine.min.js"></script>
    <!-- Valine Comments script -->
    <script>
        var GUEST_INFO = ['nick','mail','link'];
        var guest_info = 'nick,mail,link'.split(',').filter(function(item){
          return GUEST_INFO.indexOf(item) > -1
        });
        new Valine({
            el: '#comments',
            notify: 'false' == 'true',
            verify: 'false' == 'true',
            appId: "NHOU6qcrdobSwD5wwUJJ31pQ-gzGzoHsz",
            appKey: "E0RJgPMPwkjfMBOA88EalSzJ",
            avatar: "mm",
            placeholder: "Just go go",
            guest_info: guest_info.length == 0 ? GUEST_INFO : guest_info,
            pageSize: "10"
        })
    </script>
    <!-- Valine Comments end -->







</article>



</div>

        <footer class="footer">
    <div class="top">
        <p>
    <span id="busuanzi_container_site_uv">
        站点总访客数：30<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv">
        站点总访问量：425<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            
                <span><a href="/atom.xml" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            
            <span>博客内容遵循 <a rel="license" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">知识共享 署名 - 非商业性 - 相同方式共享 4.0 国际协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p><span>Edward &copy; 2017 - 2021</span>
            <span>
                
                Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://github.com/yscoder/hexo-theme-indigo" target="_blank">indigo</a>
            </span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://springcloud.xn--ses554g/2018/12/13/Effective_java_002/&title=《【Effective java第二版整理】第二条： 遇到多个构造器参数时要考虑构造器》 — Edward&pic=http://springcloud.xn--ses554g/img/123.png" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://springcloud.xn--ses554g/2018/12/13/Effective_java_002/&title=《【Effective java第二版整理】第二条： 遇到多个构造器参数时要考虑构造器》 — Edward&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://springcloud.xn--ses554g/2018/12/13/Effective_java_002/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《【Effective java第二版整理】第二条： 遇到多个构造器参数时要考虑构造器》 — Edward&url=http://springcloud.xn--ses554g/2018/12/13/Effective_java_002/&via=http://springcloud.xn--ses554g" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://springcloud.xn--ses554g/2018/12/13/Effective_java_002/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/', SHARE: true, REWARD: false };


</script>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/main.min.js"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/search.min.js" async></script>






<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>





<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"log":false,"model":{"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"right","width":200,"height":400},"mobile":{"show":false}});</script></body>
</html>
